<template>
  <a-upload
    v-model:file-list="fileList"
    name="file"
    :maxCount="1"
    :customRequest="customRequest"
    :beforeUpload="beforeUpload"
    @remove="remove"
  >
    <a-button v-if="!fileList?.length || fileList?.length < 20" :loading="loading">
      <UploadOutlined />
      上传文件
    </a-button>
  </a-upload>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { UploadOutlined } from '@ant-design/icons-vue'
import { useVModel } from '@vueuse/core'
import { message, type UploadProps } from 'ant-design-vue'
import orderupFile from '@/services/account-management/orderupFile'
import type { UploadType } from '@/services/order/upFile'

interface Props {
  img?: string
  list: UploadType[] // 父组件传递的文件列表
}

const props = defineProps<Props>()

// fileList 用于展示上传的文件
const fileList = ref<any['fileList']>([])
// 使用 useVModel 让文件列表双向绑定到父组件
const list = useVModel(props, 'list')

const emit = defineEmits(['url'])

const [, orderupFileFn, loading] = orderupFile()

// 上传图片接口
async function customRequest({ file }: any) {
  const formData = new FormData()
  formData.append('file', file)

  const [err, res] = await orderupFileFn(formData)

  if (err) {
    message.warn('上传失败')
    return
  }
  message.success('上传成功')

  const data = res.data.data
  emit('url', data)

  fileList.value = [
    {
      name: data.split('-').pop(),
      status: 'done',
      url: data,
      response: data
    }
  ]
}

async function beforeUpload(file: any) {
  return true
}

// 移除回调
function remove(file: any) {
  fileList.value = fileList.value.filter((item) => item.uid !== file.uid)
  emit('url', '')
}

// 监听 props.list 以便回显父组件传递的文件
watch(
  () => props.list,
  (val) => {
    fileList.value = []
    if (val && val.length) {
      fileList.value = val.map((item) => ({
        name: item.url.split('-').pop(),
        status: 'done',
        url: item.url,
        response: item.url
      }))
    }
  },
  { immediate: true }
)
</script>

<style lang="scss" scoped>
/* 你可以添加一些样式 */
</style>
